package com.cungmua.app.activity;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.cungmua.app.R;
import com.cungmua.app.base.BaseAuthenticatedActivity;
import com.cungmua.app.handler.EditProfileHandler;
import com.cungmua.app.model.Cart;
import com.cungmua.app.model.User;
import com.cungmua.app.model.request.EditProfileRequest;
import com.cungmua.app.model.response.EditProfileResponse;
import com.cungmua.app.task.EditProfileTask;
import com.cungmua.app.utils.AppUtils;

import java.text.SimpleDateFormat;
import java.util.Calendar;

/**
 * Created by kelvin.nguyen on 7/1/14.
 */
public class EditProfileActivity extends BaseAuthenticatedActivity implements View.OnClickListener, EditProfileHandler {

    private EditText txtName;
    private EditText txtPhone;
    private EditText txtDOB;
    private TextView txtEmail;
    private RadioButton rdMale;
    private RadioButton rdFemale;
    private Button btnUpdate;
    private int birthYear;
    private int birthMonth;
    private int birthDay;
    private User profile;
    private ImageView icon_home;
    private Button icon_cart;
    private LinearLayout btnCart;

    @Override
    public int getLayoutResource() {
        return R.layout.activity_edit_profile;
    }

    @Override
    public void updateView() {
        profile = (User) getIntent().getExtras().get(IK_USER);

        txtName.setText(profile.getName());
        SimpleDateFormat f = AppUtils.getShowDateFormatter();
        if (profile.getDateOfBirth() != null)
            txtDOB.setText(f.format(profile.getDateOfBirth()));
        txtPhone.setText(profile.getMobile());
        txtEmail.setText("Email:  "+ profile.getEmail());
        rdMale.setChecked(profile.getGender() == 0);
        rdFemale.setChecked(profile.getGender() == 1);

        Calendar cal = Calendar.getInstance();
        if (profile.getDateOfBirth() != null)
            cal.setTime(profile.getDateOfBirth());
        birthYear = cal.get(Calendar.YEAR);
        birthMonth = cal.get(Calendar.MONTH);
        birthDay = cal.get(Calendar.DAY_OF_MONTH);

        txtDOB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DatePickerDialog dialog = new DatePickerDialog(EditProfileActivity.this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker datePicker, int year, int month, int day) {
                        birthYear = year;
                        birthMonth = month;
                        birthDay = day;

                        SimpleDateFormat format = AppUtils.getShowDateFormatter();
                        Calendar cal = Calendar.getInstance();
                        cal.set(year, month, day);

                        txtDOB.setText(format.format(cal.getTime()));
                    }
                }, birthYear, birthMonth, birthDay);
                dialog.getDatePicker().setMaxDate(System.currentTimeMillis());
                dialog.show();
            }
        });

        txtDOB.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean focused) {
                if (focused) {
                    DatePickerDialog dialog = new DatePickerDialog(EditProfileActivity.this, new DatePickerDialog.OnDateSetListener() {
                        @Override
                        public void onDateSet(DatePicker datePicker, int year, int month, int day) {
                            birthYear = year;
                            birthMonth = month;
                            birthDay = day;

                            SimpleDateFormat format = AppUtils.getShowDateFormatter();
                            Calendar cal = Calendar.getInstance();
                            cal.set(year, month, day);

                            txtDOB.setText(format.format(cal.getTime()));
                        }
                    }, birthYear, birthMonth, birthDay);
                    dialog.getDatePicker().setMaxDate(System.currentTimeMillis());
                    dialog.show();
                }
            }
        });

        icon_home.setOnClickListener(new ImageView.OnClickListener() {
            @Override
            public void onClick(View v) {
                showMenu();
            }
        });

        btnCart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goToYourCart();
            }
        });


    }

    @Override
    public void loadControls(Bundle savedInstanceState) {
        txtName = (EditText) findViewById(R.id.txtName);
        txtPhone = (EditText) findViewById(R.id.txtPhone);
        txtDOB = (EditText) findViewById(R.id.txtDateOfBirth);
        txtEmail = (TextView) findViewById(R.id.txtEmail);
        rdMale = (RadioButton) findViewById(R.id.rdMale);
        rdFemale = (RadioButton) findViewById(R.id.rdFemale);
        btnUpdate = (Button) findViewById(R.id.btnUpdate);
        icon_home=(ImageView)findViewById(R.id.icon_home);
        btnCart=(LinearLayout)findViewById(R.id.btnCart);
        icon_cart=(Button)findViewById(R.id.icon_cart);
        btnUpdate.setOnClickListener(this);

        Cart currentCart=getCurrentCart();
        if(currentCart.getTotalQuantity()>0) {
            icon_cart.setText(currentCart.getTotalQuantity() + "");
            icon_cart.setVisibility(View.VISIBLE);
        }else{
            icon_cart.setVisibility(View.GONE);
        }
    }

    @Override
    public void onClick(View view) {
        if (!validateFields()) return;
        EditProfileRequest request = new EditProfileRequest(getDeviceId(), getToken());
        request.setUserId(profile.getId());
        profile.setName(txtName.getText().toString());
        profile.setMobile(txtPhone.getText().toString());
        Calendar cal = Calendar.getInstance();
        cal.set(birthYear, birthMonth, birthDay);
        profile.setDateOfBirth(cal.getTime());
        if (rdFemale.isChecked())
            profile.setGender(1);
        else
            profile.setGender(0);

        request.setUser(profile);

        EditProfileTask task = new EditProfileTask(this, this);

        task.execute(request);
    }


    public void alert(String alert) {
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setMessage(alert + getToken())
                .setNeutralButton(R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                })
                .show();
    }

    private boolean validateFields() {
        if (txtName.getText().toString().isEmpty()) {
            alert(getString(R.string.must_have_name));
            return false;
        }
        if (txtPhone.getText().toString().isEmpty()) {
            alert(getString(R.string.must_have_phone));
            return false;
        }
        if (txtDOB.getText().toString().isEmpty()) {
            alert(getString(R.string.must_have_dob));
            return false;
        }
        if (!rdMale.isChecked() && !rdFemale.isChecked()) {
            alert(getString(R.string.must_choose_gender));
            return false;
        }
        if (txtPhone.getText().toString().length() < 10 || txtPhone.getText().toString().length() > 11 ||
                !txtPhone.getText().toString().startsWith("0")) {
            alert("Số điện thoại nhập không đúng. Vui lòng nhập lại.");
            return false;
        } else if (txtPhone.getText().toString().startsWith("02") ||
                txtPhone.getText().toString().startsWith("03") || txtPhone.getText().toString().startsWith("04") ||
                txtPhone.getText().toString().startsWith("05") || txtPhone.getText().toString().startsWith("06") ||
                txtPhone.getText().toString().startsWith("07") || txtPhone.getText().toString().startsWith("08")) {
            alert("Số điện thoại nhập không đúng. Vui lòng nhập lại.");
            return false;
        } else if (txtPhone.getText().toString().startsWith("09") && txtPhone.getText().toString().length() != 10) {
            alert("Số điện thoại nhập không đúng. Vui lòng nhập lại.");
            return false;
        } else if (txtPhone.getText().toString().startsWith("01") && txtPhone.getText().toString().length() != 11) {
            alert("Số điện thoại nhập không đúng. Vui lòng nhập lại.");
            return false;
        }
        if (!txtPhone.getText().toString().matches("[0-9]+")) {
            alert("Số điện thoại nhập không đúng. Vui lòng nhập lại.");
            return false;
        }
        return true;
    }

    @Override
    public void onEditProfile(EditProfileResponse response) {
        if (response.getCode() == 0) {
            Toast.makeText(this, R.string.profile_updated, Toast.LENGTH_LONG).show();
            profile.setToken(getToken());
            setCurrentUser(profile);
            setResult(RESULT_OK);
            finish();
        } else {
            alert(response.getMessage());
        }
    }


}